package com.fingard.dsp.bank.directbank.cmbc11;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directConfig.FtpSet;
import com.fingard.dsp.bank.directbank.FailCode;
import com.fingard.dsp.bank.directbank.PaymentState;
import com.fingard.dsp.bank.directbank.bankInterface.IBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.ReqBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.ReqQryBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.RetAtsBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.RetAtsQryBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.detail.RetAtsBatPayRecDetail;
import com.fingard.io.FileHelper;
import com.fingard.net.*;
import com.fingard.text.StringHelper;

import java.io.BufferedReader;
import java.io.File;
import java.io.StringReader;
import java.text.MessageFormat;

/**
 * CMBC11-民生银行银保通(和谐健康保险专用)
 */
public class CMBC11BatPayRec extends CMBC11Base implements IBatPayRec {
    @Override
    public RetAtsBatPayRec d_1988_BatPay(ReqBatPayRec p_req1988) throws Exception {
        return d_BatPayRec(p_req1988);
    }

    @Override
    public RetAtsQryBatPayRec d_1998_QryBatPay(ReqQryBatPayRec p_req1998) throws Exception {
        return d_QryBatPayRec(p_req1998);
    }

    @Override
    public RetAtsBatPayRec d_9188_BatPay(ReqBatPayRec p_req9188) throws Exception {
        return d_BatPayRec(p_req9188);
    }

    @Override
    public RetAtsQryBatPayRec d_9198_QryBatPay(ReqQryBatPayRec p_req9198) throws Exception {
        return d_QryBatPayRec(p_req9198);
    }

    /**
     * 批量代收付提交
     *
     * @param p_reqBat 批量代收付请求对象
     * @return 批量代收付响应对象
     * @throws Exception
     */
    public RetAtsBatPayRec d_BatPayRec(ReqBatPayRec p_reqBat) throws Exception {
        RetAtsBatPayRec retAts = new RetAtsBatPayRec(p_reqBat.reqHeader);
        retAts.reqSeqID = p_reqBat.reqBatchNO;

        try {
            // 代收付文件内容
            StringBuilder sbFileContent = new StringBuilder();

            String tmpPaySendDate = Format.Date8Format.format(getDayCutTime(p_reqBat.getPayDateTime()));
            String cdFlag = "S";
            if ("1988".equalsIgnoreCase(p_reqBat.reqHeader.transType)) {
                cdFlag = "F";
            }

            // 汇总信息：保险公司代码|银行代码|申请日期|业务性质|总金额（单位：元）|总笔数
            String tmpReqHeader = MessageFormat.format("{0}|{1}|{2}|{3}|{4}|{5}\r\n", bankFront.corpNo,bankFront.serverCode,tmpPaySendDate,cdFlag, p_reqBat.totalAmt, p_reqBat.totalNum);
            sbFileContent.append(tmpReqHeader);

            // 文件明细
            while (p_reqBat.readRecord()) {
                String postScript = p_reqBat.readedDetail.askNumber;

                String oppAct = "";
                String oppName = "";
                if ("1988".equals(p_reqBat.reqHeader.transType)) {
                    oppAct = p_reqBat.readedDetail.recAct;
                    oppName = p_reqBat.readedDetail.recName;
                } else {
                    oppAct = p_reqBat.readedDetail.payAct;
                    oppName = p_reqBat.readedDetail.payName;
                }

                String payAmt = p_reqBat.readedDetail.payAmount;
                String certType = convertCertTypeToBank(p_reqBat.readedDetail.certType);
                String certNum = p_reqBat.readedDetail.certNum;

                String sourceNoteCode = getBankConfig().getValueAsString("sourceNoteCode");
                if (StringHelper.hasAnyChar(sourceNoteCode)) {
                    sourceNoteCode = p_reqBat.readedDetail.srcXElement.getSingleText(sourceNoteCode);
                }
                String saleType = getBankConfig().getValueAsString("saleType");
                if (StringHelper.hasAnyChar(saleType)) {
                    saleType = p_reqBat.readedDetail.srcXElement.getSingleText(saleType);
                }
                String branchBank = getBankConfig().getValueAsString("branchBank");
                if (StringHelper.hasAnyChar(branchBank)) {
                    branchBank = p_reqBat.readedDetail.srcXElement.getSingleText(branchBank);
                }
                String sellerCode = getBankConfig().getValueAsString("sellerCode");
                if (StringHelper.hasAnyChar(sellerCode)) {
                    sellerCode = p_reqBat.readedDetail.srcXElement.getSingleText(sellerCode);
                }
                String busType = getBankConfig().getValueAsString("busType");
                if (StringHelper.hasAnyChar(sellerCode)) {
                    busType = p_reqBat.readedDetail.srcXElement.getSingleText(busType);
                }
                String remark = getBankConfig().getValueAsString("remark");
                if (StringHelper.hasAnyChar(remark)) {
                    remark = p_reqBat.readedDetail.srcXElement.getSingleText(remark);
                }

                // 明细信息:批次号|流水号|客户银行帐号|金额（单位：元）|保单号|客户姓名|银行业务员代码|银行代码（支行）|业务类型|销售方式|备用\r\n
                String tmpReqBodyDetail = MessageFormat.format("{0}|{1}|{2}|{3}|{4}|{5}|{6}|{7}|{8}|{9}|{10}\r\n", p_reqBat.reqBatchNO, postScript,oppAct,payAmt,sourceNoteCode,oppName, sellerCode, branchBank,busType,saleType,remark);
                sbFileContent.append(tmpReqBodyDetail);
            }
            WriteBankLogLn2("批量代收付请求文件内容:\r\n" + sbFileContent.toString());

            String tmpUploadFileName = "YBTRQ" + cdFlag + bankFront.serverCode+bankFront.corpNo + tmpPaySendDate;
            String tmpLocalMarkPath = getTempFileDirectory() + File.separator + tmpUploadFileName;
            WriteBankLogLn2("批量代收付请求文件保存本机路径: " + tmpLocalMarkPath);
            if (FileHelper.existFile(tmpLocalMarkPath)) {
                retAts.respCode = "0";
                retAts.respInfo = "本地批次文件已上传,请勿重复上传!";
                retAts.reqSeqID = p_reqBat.reqBatchNO;
                retAts.transState = PaymentState.FAIL_Batch;
                retAts.payInfoCode = FailCode.E9981;
                retAts.writeRetToATS();
                return retAts;
            }
            FileHelper.writeFile(tmpLocalMarkPath, sbFileContent.toString(), getCharset());

            // 上送银保通服务器
            FtpSet ftpSet = bankFront.getFtpSet("bat");
            MixFtp mixFtp = new MixFtp(ftpSet);
            String directDir = "";
            if(getBankConfig().getValueAsBool("useDateFtpPath")) {
                String tmpDate = Format.Date8Format.format(p_reqBat.getPayDateOnly());
                if (ftpSet.upDir.endsWith("/")) {
                    directDir = tmpDate;
                } else {
                    directDir = "/" + tmpDate;
                }
            }
            ftpSet.upDir = ftpSet.upDir + directDir;
            FtpReceiver ftpReceiver = mixFtp.uploadFileToDir(tmpLocalMarkPath, ftpSet.upDir, tmpUploadFileName);

            retAts.respCode = "0";
            if (!ftpReceiver.isCompleted) {
                retAts.respCode = "-1";
                retAts.respInfo = ftpReceiver.connMsg;
            } else if (ConnState.FAIL.equals(ftpReceiver.connState)) {
                retAts.respInfo = "上传失败";
                retAts.transState = "BatchFailed";
                retAts.payInfoCode = "E9999";
            } else {
                retAts.respInfo = "上传成功";
                retAts.transState = "Uploaded";
                retAts.payInfoCode = "I4001";
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            retAts.respCode = "-1";
            retAts.respInfo = ex.getMessage();
            WriteBankLogLn(ex);
        }

        retAts.writeRetToATS();
        return retAts;
    }

    /**
     * 批量代收付状态查询
     *
     * @param p_reqQryBat
     * @return
     * @throws Exception
     */
    public RetAtsQryBatPayRec d_QryBatPayRec(ReqQryBatPayRec p_reqQryBat) throws Exception {
        RetAtsQryBatPayRec retAts = new RetAtsQryBatPayRec(p_reqQryBat.reqHeader);
        retAts.reqSeqID = p_reqQryBat.reqBatchNO;

        try {
            String tmpPaySendDate = Format.Date8Format.format(getDayCutTime(p_reqQryBat.getBgnDateTime()));
            String cdFlag = "S";
            if ("1998".equalsIgnoreCase(p_reqQryBat.reqHeader.transType)) {
                cdFlag = "F";
            }
            String tmpDownFileName = "YBTRP" + cdFlag + bankFront.serverCode+ bankFront.corpNo + tmpPaySendDate;
            String tmpLocalMarkPath = createTempFileDirectory() + File.separator + tmpDownFileName;
            WriteBankLogLn2("批次结果文件保存本地路径: " + tmpLocalMarkPath);

            FtpSet ftpSet = bankFront.getFtpSet("bat");
            MixFtp mixFtp = new MixFtp(ftpSet);
            String directDir = "";
            if(getBankConfig().getValueAsBool("useDateFtpPath")) {
                if (ftpSet.downDir.endsWith("/")) {
                    directDir = tmpPaySendDate;
                } else {
                    directDir = "/" + tmpPaySendDate;
                }
            }
            ftpSet.downDir = ftpSet.downDir + directDir;
            FtpReceiver ftpReceiver = mixFtp.downloadFileFromDir(ftpSet.downDir, tmpDownFileName, tmpLocalMarkPath);
            if (ftpReceiver.isCompleted) {
                String tmpStrRet = FileHelper.readFileText(tmpLocalMarkPath, getCharset());
                WriteBankLogLn2("本地批次结果文件内容:\r\n" + tmpStrRet);
                if (StringHelper.hasAnyChar(tmpStrRet)) {
                    retAts.respCode = "0";

                    StringReader strReader = new StringReader(tmpStrRet);
                    BufferedReader tmpReader = new BufferedReader(strReader);
                    tmpReader.readLine();

                    while(true) {
                        String eachline = tmpReader.readLine();
                        if(StringHelper.isNullOrEmpty(eachline)){
                            break;
                        }
                        if (eachline.indexOf("|") > 0) {
                            String[] bodyValues = eachline.split("\\|");
                            if (bodyValues != null && bodyValues.length > 0) {
                                if (p_reqQryBat.reqBatchNO.equalsIgnoreCase(bodyValues[0])) {
                                    RetAtsBatPayRecDetail tmpRetDetail = new RetAtsBatPayRecDetail();

                                    if(p_reqQryBat.reqHeader.transType.equals("1998")){
                                        tmpRetDetail.recAct = bodyValues[2];
                                        tmpRetDetail.recName = bodyValues[6];
                                    } else if(p_reqQryBat.reqHeader.transType.equals("9198")){
                                        tmpRetDetail.payAct = bodyValues[2];
                                        tmpRetDetail.payName = bodyValues[6];
                                    }
                                    tmpRetDetail.postScript = bodyValues[1];
                                    tmpRetDetail.payAmount = bodyValues[3];
                                    tmpRetDetail.result = bodyValues[4];

                                    if (bodyValues.length > 11) {
                                        tmpRetDetail.memo = bodyValues[11];
                                        if (bodyValues[11].contains(":")) {
                                            tmpRetDetail.payInfoCode = bodyValues[11].split(":")[0];
                                            tmpRetDetail.memo = bodyValues[11].split(":")[1];
                                        }
                                    }

                                    retAts.writeRetDetail(tmpRetDetail);
                                }
                            }
                        } else {
                            retAts.respCode = "-1";
                            retAts.respInfo = "银行返回明细数据格式非法!";
                        }
                    }
                } else {
                    retAts.respCode = "-1";
                    retAts.respInfo = "本地批次结果文件内容为空!";
                }
            } else {
                retAts.respCode = "-1";
                retAts.respInfo = "批次结果文件下载失败:" + ftpReceiver.connMsg;
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            retAts.respCode = "-1";
            retAts.respInfo = ex.getMessage();
            WriteBankLogLn(ex);
        }

        retAts.writeAfterDetail();
        return retAts;
    }
}